<template>
  <page-view class="shop-cart">
    <page-header title="购物车" :show-back="true"></page-header>
    <div class="content-box">
      <tabs v-model:active="tabIndex" animated>
        <tab title="购物车列表">
          <list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <swipe-cell v-for="item in shopCartList" :key="item.id">
              <card
                :price="item.foodInfo.price"
                :title="item.foodInfo.food_name"
                :thumb="BaseURL + item.foodInfo.food_img"
              >
                <template #tags>
                  <stepper
                    v-model="item.count"
                    theme="round"
                    button-size="20"
                    disable-input
                    disable-minus
                    @plus="foodCountPlus(item.fid)"
                  />
                </template>
              </card>
              <template #right>
                <Button
                  square
                  text="删除"
                  type="danger"
                  class="delete-button"
                  @click="deleteMyShopCartFoodById(item.id)"
                />
              </template>
            </swipe-cell>
          </list>
        </tab>
        <tab title="收货地址">
          <address-list
            v-model="chosenAddressId"
            :list="addressInfoList"
            default-tag-text="默认"
            @add="$router.push({ name: 'AddAddressInfo' })"
            @edit="onEdit"
          />
        </tab>
      </tabs>
    </div>
    <submit-bar
      :price="allMoney"
      button-text="提交订单"
      @submit="$router.push({ name: 'order' })"
    />
  </page-view>
</template>

<script>
import {
  Tab,
  Tabs,
  List,
  SwipeCell,
  Card,
  Stepper,
  Button,
  Dialog,
  SubmitBar,
  AddressList,
  Toast,
} from "vant";
import { reactive, toRefs, onMounted, computed } from "vue";
import Api from "../utils/api";
import { useRouter } from "vue-router";
export default {
  name: "ShopCart",
  components: {
    Tab,
    Tabs,
    List,
    SwipeCell,
    Card,
    Stepper,
    Button,
    SubmitBar,
    AddressList,
    Toast,
  },
  setup() {
    const router = useRouter();
    let info = reactive({
      tabIndex: 0,
      shopCartList: [],
      loading: false,
      finished: false,
      pageCount: 0,
      pageEnd: 0,
      pageIndex: 1,
      pageStart: 1,
      totalCount: 0,
      chosenAddressId: 1,
      addressInfoList: [],
    });
    const foodCountPlus = async (fid) => {
      let results = await Api.shopCart.addToShopCart({
        fid: fid,
        count: 1,
      });
    };
    const deleteMyShopCartFoodById = (id) => {
      Dialog.confirm({
        title: "危险",
        message: "如果你删除了，可能就永远失去了",
      })
        .then(async () => {
          await Api.shopCart.deleteMyShopCartFoodById(id);
          let index = info.shopCartList.findIndex((item) => item.id == id);
          if (index != -1) info.shopCartList.splice(index, 1);
        })
        .catch(() => {});
    };
    const onLoad = async () => {};

    const getShopCartList = async (pageIndex = 1) => {
      info.loading = true;
      setTimeout(async () => {
        let results = await Api.shopCart.getListByPage({ pageIndex });
        console.log(results);
        info.pageCount = results.pageCount;
        info.pageEnd = results.pageEnd;
        info.pageIndex = +results.pageIndex;
        info.pageStart = results.pageStart;
        info.totalCount = results.totalCount;
        info.shopCartList.push(...results.listData);
        info.loading = false;
        info.finished = info.pageIndex >= info.pageCount;
      }, 1000);
    };

    const allMoney = computed(() => {
      let total = info.shopCartList
        .reduce((prev, current, index, _arr) => {
          return prev + current.count * current.foodInfo.price;
        }, 0)
        .toFixed(2);
      return total * 100;
    });

    // 地址列表
    const getMyAddressInfoList = async () => {
      let results = await Api.addressInfo.getMyAddressInfoList();
      console.log(results);
      info.addressInfoList = results.map((item) => {
        return {
          id: item.id,
          name: item.person_name,
          tel: item.phone,
          address: item.address,
          tag: item.tag,
        };
      });
    };
    const onEdit = (item, index) => {
      // console.log(item, index);
      router.push({
        name: "EditAddressInfo",
        query: {
          id: item.id,
        },
      });
    };

    onMounted(() => {
      getShopCartList();
      getMyAddressInfoList();
    });
    return {
      ...toRefs(info),
      deleteMyShopCartFoodById,
      foodCountPlus,
      onLoad,
      allMoney,
      onEdit,
    };
  },
};
</script>

<style lang="scss" scoped>
.delete-button {
  height: 100%;
}
::v-deep .van-card__content > div:first-child {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

::v-deep .van-address-list__bottom {
  position: unset;
}
</style>